﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
using GTServices.WPF.Client.ViewModels.Entities;
using System.Windows.Data;
using System.Windows;
using System.Windows.Controls;
namespace GTServices.WPF.Client.ViewModels
{
    public class PatternListPickerViewModel : Screen
    {
        private bool _hideAssociatedPatterns;

        public List<PatternViewModel> SelectedItems { get; set; } 
        public ListCollectionView Patterns { get; set; } 

        public bool HideAssociatedPatterns { 
            get { return _hideAssociatedPatterns; } 
            set { _hideAssociatedPatterns = value; 
                  NotifyOfPropertyChange(()=> HideAssociatedPatterns);
                  Patterns.Refresh();
                  NotifyOfPropertyChange(() => Patterns); 
            } 
        }

        private string _filterString;
        public string FilterString
        {
            get { return _filterString; }
            set
            {
                _filterString = value;
                NotifyOfPropertyChange(() => FilterString); 
            }
        }

        public void SelectedItemChanged(ActionExecutionContext context){
            SelectionChangedEventArgs eventArgs = context.EventArgs as SelectionChangedEventArgs;
            ListView lv = context.Source as ListView;
            if (lv != null)
            {
                this.SelectedItems.Clear();

                foreach (PatternViewModel iev in lv.SelectedItems)
                {
                    this.SelectedItems.Add(iev);
                }
            }
        }
        public void Ok()
        {
            TryClose(true); 
        }
        public void Cancel()
        {
            TryClose(false); 
        }
        public PatternListPickerViewModel(IList<PatternViewModel> patternViewModels)
        {
            Patterns = new ListCollectionView(patternViewModels as System.Collections.IList);
            this.SelectedItems = new List<PatternViewModel>(); 
            Patterns.Filter += new Predicate<object>(x =>
            {
                if (!(x is PatternViewModel))
                {
                    return false;
                }
                PatternViewModel pvm = x as PatternViewModel;
                if (HideAssociatedPatterns && 
                    pvm.Pattern.Categories.Count > 0 || 
                    (!String.IsNullOrEmpty(FilterString) &&  
                     !pvm.Pattern.PatternStr.Contains(FilterString)
                    ))
                {
                    return false;
                }
                return true;
            });
        }
    }
}
